/**
 * Copyright (c) 2014 All Rights Reserved by the SDL Group.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sdl.odata.renderer.metadata;

import com.sdl.odata.api.edm.model.EnumMember;
import com.sdl.odata.api.edm.model.EnumType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import static com.sdl.odata.MetadataDocumentConstants.ENUM_MEMBER;
import static com.sdl.odata.MetadataDocumentConstants.ENUM_TYPE;
import static com.sdl.odata.MetadataDocumentConstants.NAME;
import static com.sdl.odata.ODataRendererUtils.checkNotNull;

/**
 * <p>
 * Helper writer capable of writing {@code <EnumType>} elements.
 * </p>
 * <p>
 * Please note that it is necessary to open the XML writer used by instances of this class before calling any method,
 * and close it after the writing process is finished.
 * </p>
 */
public class MetadataDocumentEnumTypeWriter {

    private static final Logger LOG = LoggerFactory.getLogger(MetadataDocumentEnumTypeWriter.class);
    private final XMLStreamWriter xmlWriter;

    /**
     * Creates an instance of {@link MetadataDocumentEnumTypeWriter}.
     *
     * @param xmlWriter The XML writer to use. It can not be {@code null}.
     */
    public MetadataDocumentEnumTypeWriter(XMLStreamWriter xmlWriter) {
        this.xmlWriter = checkNotNull(xmlWriter);
    }

    /**
     * Write an {@code <EnumType>} element for the given {@code EnumType}.
     *
     * @param type The given complex type. It can not be {@code null}.
     * @throws javax.xml.stream.XMLStreamException If unable to write to strem
     */
    public void write(EnumType type) throws XMLStreamException {

        LOG.debug("Writing type {} of type {}", type.getName(), type.getMetaType());

        xmlWriter.writeStartElement(ENUM_TYPE);
        xmlWriter.writeAttribute(NAME, type.getName());
        for (EnumMember member : type.getMembers()) {
            xmlWriter.writeStartElement(ENUM_MEMBER);
            xmlWriter.writeAttribute(NAME, member.getName());
            xmlWriter.writeEndElement();
        }
        xmlWriter.writeEndElement();
    }
}
